package uc.org.jkas.app.admin;
import java.util.HashMap;
import java.util.ArrayList;
import uc.org.jkas.model.RolesM;
import uc.org.jkas.model.PrivilegesM;
import org.jkas.utils.Page;
public class Roles extends BackBase
{ RolesM rsm=new RolesM();
	public void index()
    {  if(IS_POST())
		{
		}
		else
		{int page=Pint("page");
		 int pagenum=20;
		 Page p=new Page(page,pagenum);
		 ArrayList<HashMap> lists=rsm.limit(p.getPos(),pagenum).count().order("role_id desc").select();
		 p.setCount(rsm.getCount());
		 assign("pageinfo",p.getInfo());
		 assign("lists",lists);
		 display();
		}
	}

	public void add()
	{
		if(IS_POST())
		{ String res=JSON_RESULT_FAILED;
		   HashMap<String,Object> data=new HashMap<String,Object>();
	       String caption=P("caption");
		   String privileges=P("privileges");
		   if(!isEmpty(caption))
			{       data.put("caption",caption);
		            data.put("privileges",privileges);
		             if(rsm.insert(data)>0)
			           {res=JSON_RESULT_SUCCESS;
			           }
			}
			else
			{res="{\"code\":401,\"msg\":\"empty name\"}";
			}
		  echo(res);
		}
		else
		{   PrivilegesM psm=new PrivilegesM();
		    HashMap<String,ArrayList> tree=psm.getPrivileges(null);
			assign("lists",tree.get("lists"));
			assign("parents",tree.get("parents"));
			display();
		}
	}

	public void edit()
	{  int role_id=Pint("role_id");
		if(IS_POST())
		{ String res=JSON_RESULT_FAILED;
		  HashMap<String,Object> data=new HashMap<String,Object>();
	      String caption=P("caption");
		  String privileges=P("privileges");
           if(!isEmpty(caption))
			{
		            data.put("caption",caption);
		            data.put("privileges",privileges);
					data.put("role_id",role_id);
					 if(rsm.update(data)>0)
			            {res=JSON_RESULT_SUCCESS;
			            }
			}
			else
			{res="{\"code\":401,\"msg\":\"empty name\"}";
			}

			echo(res);
		}
		else
		{   
			HashMap<String,String> info=rsm.getInfo(role_id);
			String[] privis=info.get("privileges").split(",");
			PrivilegesM psm=new PrivilegesM();
		    HashMap<String,ArrayList> tree=psm.getPrivileges(privis);
			assign("lists",tree.get("lists"));
			assign("parents",tree.get("parents"));
			assign("info",info);
			display();
		}
	}

	public void drop()
	{ String res=JSON_RESULT_FAILED;
	   if(IS_POST())
		{
		  int role_id=Pint("role_id");
	      if(role_id>0 && rsm.dropInfo(role_id)>0)
		  {res=JSON_RESULT_SUCCESS;
		  }
		}
		echo(res);
	}

}